import BaseAction from '@/components/base/BaseAction';
import BaseButton from '@/components/base/BaseButton';
import { useModal } from '@/components/base/BaseModal';
import BasePageFrame from '@/components/base/BasePageFrame';
import BaseTable from '@/components/base/BaseTable';
import BaseTree from '@/components/base/BaseTree';
import { EnumValueType } from '@/utils/enum';
import { useRequest } from '@/utils/request';
import {
  DeleteOutlined,
  EditOutlined,
  FileOutlined,
  FolderOpenOutlined,
  FolderOutlined,
  LeftOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-table';
import { Button, Card, Descriptions, Empty, Space } from 'antd';
import { useRef, useState } from 'react';
import { PageModel as IPageInfo, PageType } from '../data';
import {
  deleteFunctionBlockInfo,
  deletePageInfo,
  getFunctionBlockInfoList,
  getPageInfoList,
  getPageTree
} from './api';
import FunctionBlockInfoModal from './modals/FunctionBlockInfoModal';
import PageInfoModal from './modals/PageInfoModal';

const PageInfo = () => {
  const tableRef = useRef<ActionType>();
  const fbTableRef = useRef<ActionType>();
  const [cur, setCur] = useState<IPageInfo>({} as IPageInfo);
  const [expand, setExpand] = useState<string[]>([]);
  const setCurPage = (page: IPageInfo) => {
    setCur(page);
    if (page.permissionPid) {
      setExpand([...expand, page.permissionPid]);
    }
  };
  const pagetree = useRequest(getPageTree);
  const del = useRequest(deletePageInfo, {
    manual: true,
    fetchKey: (id) => id,
    onSuccess() {
      pagetree.run();
      tableRef.current?.reload();
    }
  });
  const delfb = useRequest(deleteFunctionBlockInfo, {
    fetchKey: (id) => id,
    manual: true,
    onSuccess() {
      pagetree.run();
      fbTableRef.current?.reload();
    }
  });
  const pageInfoModal = useModal(PageInfoModal, {
    onSuccess() {
      // setCur(data);
      pagetree.run();
      tableRef.current?.reload();
    }
  });

  const functionBlockInfoModal = useModal(FunctionBlockInfoModal, {
    onSuccess() {
      fbTableRef.current?.reload();
    }
  });

  const backTopLevel = () => {
    setCurPage({} as IPageInfo);
  };
  return (
    <BasePageFrame bodyFlex>
      <Card style={{ flexBasis: 300, flexShrink: 1 }}>
        <BaseTree
          blockNode
          expandedKeys={expand}
          selectedKeys={[cur.id]}
          treeData={pagetree.data || []}
          showIcon
          icon={(node) => {
            // eslint-disable-next-line no-nested-ternary
            return (node as unknown as { type: EnumValueType<typeof PageType['enum']> }).type ===
              PageType.enum.页面 ? (
              <FileOutlined />
            ) : node.expanded ? (
              <FolderOpenOutlined />
            ) : (
              <FolderOutlined />
            );
          }}
          bindProps={{ key: 'id', title: 'label', value: 'id', children: 'permissionTreeVOList' }}
          onExpand={(expandedKeys) => {
            setExpand(expandedKeys as string[]);
          }}
          onSelect={(selectkeys, e) => {
            if (selectkeys.length > 0) {
              setCurPage(e.node as unknown as IPageInfo);
            }
          }}
        />
      </Card>
      <div style={{ flex: '1 1 0%', overflow: 'hidden' }}>
        <Card>
          {cur.id ? (
            <Descriptions
              title={`当前${PageType.getLabelByValue(cur.type)}信息`}
              extra={
                <Space>
                  <Button icon={<LeftOutlined />} onClick={backTopLevel}>
                    退回顶层
                  </Button>
                  <BaseButton
                    type='primary'
                    code='edit'
                    icon={<EditOutlined />}
                    onClick={() => {
                      pageInfoModal.load({ data: cur });
                    }}
                  >
                    编辑
                  </BaseButton>
                </Space>
              }
            >
              <Descriptions.Item label='名称'>{cur.label}</Descriptions.Item>
              <Descriptions.Item label='标识'>{cur.router}</Descriptions.Item>
              <Descriptions.Item label='类型'>
                {PageType.getLabelByValue(cur.type)}
              </Descriptions.Item>
              <Descriptions.Item span={3} label='备注'>
                {cur.remarks}
              </Descriptions.Item>
            </Descriptions>
          ) : (
            <Empty description='当前已是根页面，暂无具体数据' />
          )}
        </Card>
        {cur.type === PageType.enum.页面 ? (
          <BaseTable
            key='page'
            actionRef={fbTableRef}
            headerTitle='页面模块列表'
            params={{ pageId: cur.id }}
            request={getFunctionBlockInfoList}
            toolBarRender={() => [
              <BaseButton
                type='primary'
                code='create'
                icon={<PlusOutlined />}
                onClick={() => {
                  functionBlockInfoModal.load({ pageId: cur.id });
                }}
              >
                新增模块
              </BaseButton>
            ]}
            columns={[
              { dataIndex: 'name', title: '模块名称', fixed: 'left' },
              { dataIndex: 'router', title: '标识' },
              { dataIndex: 'description', title: '描述' },
              {
                title: '操作',
                fixed: 'right',
                render: (text, record) => {
                  return (
                    <Space>
                      <BaseAction
                        color='green'
                        icon={<EditOutlined />}
                        title='编辑'
                        code='edit'
                        onClick={() => {
                          functionBlockInfoModal.load({ data: record, pageId: cur.id });
                        }}
                      />
                      <BaseAction
                        color='red'
                        icon={<DeleteOutlined />}
                        title='删除'
                        code='delete'
                        loading={delfb.fetches[record.id]?.loading}
                        onClick={() => {
                          delfb.run(record.id);
                        }}
                      />
                    </Space>
                  );
                }
              }
            ]}
          />
        ) : (
          <BaseTable
            key='menu'
            actionRef={tableRef}
            headerTitle='子页面列表'
            params={{ id: cur.id }}
            request={getPageInfoList}
            rowKey='id'
            toolBarRender={() => [
              <BaseButton
                type='primary'
                code='create'
                icon={<PlusOutlined />}
                onClick={() => {
                  pageInfoModal.load({ parentID: cur.id });
                }}
              >
                新增页面
              </BaseButton>
            ]}
            columns={[
              {
                dataIndex: 'label',
                title: '名称',
                fixed: 'left',
                render: (text, record) => {
                  return (
                    <Button
                      type='link'
                      onClick={() => {
                        setCurPage(record);
                      }}
                    >
                      {text}
                    </Button>
                  );
                }
              },
              { dataIndex: 'router', title: '标识' },
              { dataIndex: 'sort', title: '排序' },
              { dataIndex: 'type', title: '类型', renderText: PageType.getLabelByValue },
              { dataIndex: 'actionUrl', title: '页面URL' },
              { dataIndex: 'remarks', title: '备注' },
              {
                title: '操作',
                fixed: 'right',
                render: (t, record) => {
                  return (
                    <Space>
                      <BaseAction
                        color='green'
                        title='编辑'
                        code='edit'
                        icon={<EditOutlined />}
                        onClick={() => {
                          pageInfoModal.load({ data: record, parentID: cur.id });
                        }}
                      />
                      <BaseAction
                        color='red'
                        title='删除'
                        code='delete'
                        icon={<DeleteOutlined />}
                        loading={del.fetches[record.id]?.loading}
                        onClick={() => {
                          del.run(record.id);
                        }}
                      />
                    </Space>
                  );
                }
              }
            ]}
          />
        )}
      </div>
    </BasePageFrame>
  );
};

export default PageInfo;
